package com.ys.util.baidu;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.squareup.okhttp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class ApiHttpClientUtils {
    private static final Logger logger = LoggerFactory.getLogger(ApiHttpClientUtils.class);

    public JSONObject sendHttpPost(Map<String, Object> params, String url) throws IOException {
        //参数格式转换
        ObjectMapper objectMapper = new ObjectMapper();
        String sentStr = objectMapper.writeValueAsString(params);
        //接口参数设置
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, sentStr);
        logger.info("发送参数："+sentStr);
        Request apiRequest = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        //返回参数
        Response apiResponse = client.newCall(apiRequest).execute();
        JSONObject result =JSONObject.parseObject(apiResponse.body().string());
        return result;
    }






}
